package logic

import (
	"errors"
	"web_app/dao/mysql"
	"web_app/models"
	"web_app/pkg/jwt"
	"web_app/pkg/snowflake"
)

func SignUp(p *models.ParamSignUp) (err error) {
	// 判断用户存在
	err = mysql.CheckUserExist(p.Username)
	if err != nil {
		return errors.New("用户已存在")
	}
	// 生成UID
	userId := snowflake.GetID()
	user := &models.User{
		UserID:   userId,
		Username: p.Username,
		Password: p.Password,
	}
	// 保存进数据库
	return mysql.InsertUser(user)
}

func Login(p *models.ParamLogin) (token string, err error) {
	user := &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	//传递的是指针，就能拿到id
	if err = mysql.Login(user); err != nil {
		return
	}
	//生成jwt的token
	return jwt.GenToken(user.UserID, user.Username)
}
